package com.zz.common.serialize;

import com.zz.common.annotation.Serialize;
import com.zz.common.enums.SerializationType;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 序列化工厂
 *
 * @author zz
 */
@Slf4j
public class SerializeFactory {

    private final static Map<SerializationType, SerializerDispatcher> serializeCache = new ConcurrentHashMap<>();

    static {
        ServiceLoader<SerializerDispatcher> dispatchers = ServiceLoader.load(SerializerDispatcher.class);
        for (SerializerDispatcher dispatcher : dispatchers) {
            Serialize annotation = dispatcher.getClass().getAnnotation(Serialize.class);
            if (Objects.isNull(annotation)) {
                continue;
            }
            serializeCache.put(annotation.value(), dispatcher);
        }
    }

    public static SerializerDispatcher getInstances(byte serializeType) {
        SerializerDispatcher dispatcher = serializeCache.get(SerializationType.getInstance(serializeType));
        if (Objects.isNull(dispatcher)) {
            log.error("获取序列化处理器失败！");
            return new Protostuff();
        }
        return dispatcher;
    }



}
